package com.shenzhenai.netease_handler_1_3_1_3.core;


/**
 * @author huangzehui
 * @date 25/4/2025 上午9:28 周五
 * @description
 */
public class Handler {

    private Looper mLooper;
    private MessageQueue mQueue;

    private Callback callback;

    public interface Callback {

        boolean handleMessage(Message msg);
    }

    public Handler() {
        this(null);
    }

    public Handler(Callback callback) {
        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                    "Can't create handler inside thread " + Thread.currentThread()
                            + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        this.callback = callback;
    }

    public void sendMessage(Message message) {
        enqueueMessage(message);
    }

    private void enqueueMessage(Message message) {
        message.target = this;
        mQueue.enqueueMessage(message);
    }

    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (callback != null) {
                if (callback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

    // 给开发者提供的开放API，用于重写和回调监听
    public void handleMessage(Message msg) {
    }

    private static void handleCallback(Message message) {

    }
}
